//分享官账户详情
import React from 'react'
import { Descriptions, Space, Modal, message, Input, Form, Button, InputNumber, Tooltip } from "antd";
import TheButton from '@/components/TheButton'
import GoBack from '@/components/TheGoBack'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import { sharerAccountDetails, updateSharerAccountStatus, freezeOrUnfreezeIncome, sharerFreezeIncomeDetailsPage } from '@/request/distribution/sharerAccount.js'
const { TextArea } = Input
export default class SharerAccountDetails extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      memberId: null, //用户id
      info: null,//信息详情
      detailsData: null,// 详情信息
      memberInfoData: [], //会员信息
      accountInfoData: [],//账户信息
      isFrozenPriceModal: false,//冻结金额弹窗
      submitLoading: false,//确认按钮loading
      isThawPriceModal: false,//解冻金额弹窗
      isFrozenRecordModal: false,//冻结金额记录弹窗
      columns: [
        {
          title: "冻结类型",
          dataIndex: "category",
          key: "category",
          render: (text) => {
            let category = ''
            switch (text) {
              case 0:
                category = '冻结'
                break
              case 1:
                category = '解冻'
                break
              default:
                category = '-'
            }
            return category
          }
        },
        {
          title: "类型",
          dataIndex: "detailType",
          key: "detailType",
          render: (text) => {
            let detailType = ''
            switch (text) {
              case 1:
                detailType = '人工操作'
                break
              default:
                detailType = '-'
            }
            return detailType
          }
        },
        {
          title: "金额",
          dataIndex: "freezeAmount",
          key: "freezeAmount",
          render: (text, record) => {
            if (record.category === 0) {
              return '-' + React.$transNum(text || 0, 2, -2)
            } else if (record.category === 1) {
              return '+' + React.$transNum(text || 0, 2, -2)
            }

          }
        },
        {
          title: "冻结备注",
          dataIndex: "remark",
          key: "remark",
          render: (text) => {
            return <Tooltip title={text}>
              <span style={{ width: 200, display: 'block', margin: 'auto', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: "ellipsis" }}>{text}</span>
            </Tooltip>
          }
        },
        {
          title: "操作时间",
          dataIndex: "createTime",
          key: "createTime",
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      sharerAccountStatus: null,//账户状态
    }
  }
  componentDidMount() {
    let { id } = this.props.match.params
    if (id) {
      this.getData(id)
    }
  }
  //数据处理
  getData = async (memberId) => {
    await sharerAccountDetails(memberId).then(res => {
      if (res.code === 0) {
        let info = res.data, sharerAccountStatus = '', memberStatus = ''
        //账户状态
        switch (info.sharerAccountStatus) {
          case 0:
            sharerAccountStatus = '正常'
            break
          case 1:
            sharerAccountStatus = '禁用'
            break
          default:
            sharerAccountStatus = '-'
            break
        }
        //会员状态
        switch (info.memberStatus) {
          case 'Y':
            memberStatus = '正常'
            break
          case 'N':
            memberStatus = '禁用'
            break
          default:
            memberStatus = '-'
            break
        }
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        if(info.memberMobile) {
          info.memberMobile = info.memberMobile.toString().replace(reg, '$1****$2');
        }
        this.setState({
          memberId,
          memberInfoData: [
            {
              label: '会员ID',
              content: info.memberId
            },
            {
              label: '用户昵称',
              content: info.nickName
            },
            {
              label: '实名姓名',
              content: info.realName ?  info.realName[0] + "*".repeat(info.realName.length - 1) : '未实名'
            },
            {
              label: '会员手机号',
              content: info.memberMobile
            },
            {
              label: '会员状态',
              content: memberStatus
            },
            {
              label: '账户状态',
              content: info.sharerAccountStatusContent
            },
          ],
          accountInfoData: [
            {
              label: '账户金额',
              content: React.$transNum(info.sharerTotalAvailableAmount, 2, -2)
            },
            {
              label: '冻结金额',
              content: <TheButton onClick={() => { this.frozenPriceRecord(info.memberId) }}>{React.$transNum(info.sharerFrozenAmount, 2, -2)}</TheButton>
            },
            {
              label: '可提现金额',
              content: React.$transNum(info.sharerAvailableAmount, 2, -2)
            },
            {
              label: '查看详情',
              content: <TheButton haspermi={['distribution:sharerAccount:particulars']} onClick={() => { this.props.history.push('/distribution/sharerAccount/particulars/' + info.memberId) }}>查看账户明细</TheButton>
            }
          ],
          info,
        })
      }
    })

  }
  //打开冻结弹窗
  frozenPriceModal = () => {
    let { memberId, nickName } = this.state.info
    this.setState({ isFrozenPriceModal: true }, () => {
      this.formRef.setFieldsValue({ memberInfo: `${nickName}(${memberId})` }) //表单渲染会员信息
    })
  }
  // 校验表单的冻结金额
  frozenPriceRules = (rule, value, callback) => {
    let { sharerAvailableAmount } = this.state.info
    if (value === undefined || value === null || value === '') {
      callback('请输入冻结金额')
    } else if (value <= 0) {
      callback('冻结金额需大于0')
    } else if (value > React.$transNum(sharerAvailableAmount, 2, -2)) {
      callback('冻结金额不能大于可用收益')
    }
    callback()
  }
  // 确认冻结金额
  frozenSubmit = (values) => {
    this.setState({ submitLoading: true }, () => {
      this.submitFreezeOrUnfreezePrice(values, 0,)
    })
  }
  //取消、关闭冻结金额弹窗
  cancelFrozen = () => {
    this.setState({ isFrozenPriceModal: false }, () => {
      this.formRef.resetFields()
    })
  }
  //打开解冻金额弹窗
  thawPriceModal = () => {
    let { memberId, nickName } = this.state.info
    this.setState({ isThawPriceModal: true }, () => {
      this.formThawRef.setFieldsValue({ memberInfo: `${nickName}(${memberId})` }) //表单渲染会员信息
    })
  }
  // 校验表单的解冻金额
  thawPriceRules = (rule, value, callback) => {
    let { sharerFrozenAmount } = this.state.info
    if (value === undefined || value === null || value === '') {
      callback('请输入解冻金额')
    } else if (value < 0) {
      callback('解冻金额需大于0')
    } else if (value > React.$transNum(sharerFrozenAmount, 2, -2)) {
      callback('解冻金额不能大于冻结余额')
    }
    callback()
  }
  //冻结、解冻金额接口
  submitFreezeOrUnfreezePrice = async (values, type) => {
    let { memberId } = this.state
    if (values && values.hasOwnProperty('memberInfo')) {
      delete values.memberInfo
    }
    if (values && values.hasOwnProperty('amount')) {
      values.amount = React.$transNum(values.amount, 0, 2)
    }
    await freezeOrUnfreezeIncome({ ...values, type, memberId: memberId }).then(res => {
      if (res.code === 0) {
        message.success('操作成功')
        if (type === 0) {
          this.cancelFrozen()
        } else if (type === 1) {
          this.cancelThaw()
        }
        this.getData(memberId)
      }
    })
    this.setState({ submitLoading: false })
  }
  // 确认解冻金额
  thawSubmit = (values) => {
    this.setState({ submitLoading: true }, () => {
      this.submitFreezeOrUnfreezePrice(values, 1)
    })
  }
  //取消、关闭解冻金额弹窗
  cancelThaw = () => {
    this.setState({ isThawPriceModal: false, }, () => {
      this.formThawRef.resetFields()
    })
  }
  // 账户状态修改
  editSharerAccountStatus = async (memberId, sharerAccountStatus) => {
    await updateSharerAccountStatus({ memberId, sharerAccountStatus }).then(res => {
      if (res.code === 0) {
        message.success('操作成功！')
        this.getData(memberId)
      }
    })
    this.setState({ editStatusBtnLoading: false })
  }
  // 禁封账户
  closedAccount = (value) => {
    this.setState({ editStatusBtnLoading: true }, () => {
      if (value.sharerAccountStatus === 0) {
        Modal.confirm({
          title: '封禁账户',
          content: '封禁账户后，用户可以正常收到佣金，但不能提现',
          onOk: async () => {
            this.editSharerAccountStatus(value.memberId, 1)
          },
          onCancel: () => {
            this.setState({ editStatusBtnLoading: false })
          }
        })
      } else if (value.sharerAccountStatus === 1) {
        this.editSharerAccountStatus(value.memberId, 0)
      }
    })
  }
  // 冻结解冻记录
  getFrozenRecordData = async (memberId) => {
    await sharerFreezeIncomeDetailsPage({ ...this.state.pageData, memberId }).then(res => {
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  // 冻结金额记录
  frozenPriceRecord = (memberId) => {
    this.setState({ isFrozenRecordModal: true }, () => {
      this.getFrozenRecordData(memberId)
    })
  }
  //分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getFrozenRecordData(this.state.memberId)
    })
  }

  render() {
    const { memberInfoData, accountInfoData, info, isFrozenPriceModal, submitLoading, isThawPriceModal, isFrozenRecordModal, columns, dataSource, pageData: { pageNo, pageSize }, total, editStatusBtnLoading } = this.state
    return (
      <div className='p-layout-box'>
        <GoBack history={this.props.history} title='分享官账户详情'></GoBack>
        <Descriptions style={{ margin: '20PX 0' }} title="会员信息" layout="vertical" bordered column={6} >
          {
            memberInfoData && memberInfoData.map((item, index) => {
              return <Descriptions.Item style={{ textAlign: 'center' }} key={index} label={item.label}>{item.content}</Descriptions.Item>
            })
          }
        </Descriptions>
        <Descriptions style={{ margin: '20PX 0' }} title="账户信息" layout="vertical" bordered column={4} >
          {
            accountInfoData && accountInfoData.map((item, index) => {
              return <Descriptions.Item style={{ textAlign: 'center' }} key={index} label={item.label}>{item.content}</Descriptions.Item>
            })
          }
        </Descriptions>
        {
          info && <Space style={{ margin: 'auto' }} size={20}>
            {info.sharerFrozenAmount > 0 && <TheButton haspermi={['distribution:sharerAccount:thawPrice']} type='default' size='middle' onClick={() => { this.thawPriceModal() }}>解冻金额</TheButton>}
            <TheButton haspermi={['distribution:sharerAccount:frozenPrice']} type='primary' size='middle' onClick={() => { this.frozenPriceModal() }}>冻结金额</TheButton>
            {/*{info.sharerAccountStatus === 1 && <TheButton haspermi={['distribution:sharerAccount:closedAccount']} type='primary' size='middle' loading={editStatusBtnLoading} onClick={() => { this.closedAccount(info) }}>解封账户</TheButton>}*/}
            {/*{info.sharerAccountStatus === 0 && <TheButton haspermi={['distribution:sharerAccount:banAccount']} type='primary' danger size='middle' loading={editStatusBtnLoading} onClick={() => { this.closedAccount(info) }}>封禁账户</TheButton>}*/}
          </Space>
        }
        {/* 冻结金额按钮弹窗 */}
        <Modal title="冻结金额" open={isFrozenPriceModal} footer={null} onCancel={() => { this.cancelFrozen() }} >
          <Form
            ref={(ref) => this.formRef = ref}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            onFinish={this.frozenSubmit}
            onValuesChange={this.onValuesChange}>
            <Form.Item label="会员" name='memberInfo' required >
              <Input bordered={false} disabled style={{ color: 'black' }} />
            </Form.Item>
            <Form.Item label="冻结金额" required>
              <Space>
                <Form.Item
                  name="amount"
                  noStyle
                  rules={[{ required: true, validator: this.frozenPriceRules }]}
                >
                  <InputNumber placeholder='请输入冻结金额' precision={2} />
                </Form.Item>
                {info && <span>可用金额：{React.$transNum(info.sharerAvailableAmount || 0, 2, -2)}</span>}
              </Space>
            </Form.Item>
            <Form.Item label="备注" name='remark' rules={[{ required: true }]}>
              <TextArea maxLength={200} placeholder='请输入备注，200字以内' autoSize={{ minRows: 1, maxRows: 6 }} />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
              <Space>
                <Button onClick={() => { this.cancelFrozen() }}>取消</Button>
                <Button type="primary" htmlType="submit" loading={submitLoading}>确定</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
        {/* 解冻金额按钮弹窗 */}
        <Modal title="解冻金额" open={isThawPriceModal} footer={null} onCancel={() => { this.cancelThaw() }} >
          <Form
            ref={(ref) => this.formThawRef = ref}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            onFinish={this.thawSubmit}
            onValuesChange={this.onValuesChange}>
            <Form.Item label="会员" name='memberInfo' required >
              <Input bordered={false} disabled style={{ color: 'black' }} />
            </Form.Item>
            <Form.Item label="解冻金额" required>
              <Space>
                <Form.Item
                  name="amount"
                  noStyle
                  rules={[{ required: true, validator: this.thawPriceRules }]}
                >
                  <InputNumber placeholder='请输入解冻金额' precision={2} />
                </Form.Item>
                {info && <span>冻结金额：{React.$transNum(info.sharerFrozenAmount, 2, -2)}</span>}
              </Space>
            </Form.Item>
            <Form.Item label="备注" name='remark' rules={[{ required: true }]}>
              <TextArea maxLength={200} placeholder='请输入备注，200字以内' />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
              <Space>
                <Button onClick={() => { this.cancelThaw() }}>取消</Button>
                <Button type="primary" htmlType="submit" loading={submitLoading}>确定</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
        {/* 冻结金额明细 */}
        <Modal title="冻结解冻记录" width={'70%'} open={isFrozenRecordModal} footer={null} onCancel={() => { this.setState({ isFrozenRecordModal: false, pageData: { pageNo: 1, pageSize: 10 } }) }} >
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            rowKey={'userId'}
          />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </Modal >
      </div >
    )
  }
}
